import * as signalR from '@microsoft/signalr';
import Global from "@/Global";
import { Toast } from 'vant';
const hubServer = process.env.VUE_APP_BASE_URL + '/chathub'

export default {
    userID: '',
    connection: null,
    //得到vue
    context: null,
    init(vue, userId, token) {
        this.userID = userId;
        this.context = vue;
        this.connection = new signalR.HubConnectionBuilder()
            .withUrl(hubServer, { accessTokenFactory: () => token })
            .withAutomaticReconnect([2000, 5000, 10000, 15000, 30000])
            .configureLogging(signalR.LogLevel.Information)
            .build();

        this.connection.on('BindResult', (toUserID, connID) => {
            // Toast.success('BindResult'+connID)
            console.log("BindResult", toUserID, connID)
        })

        this.connection.on('ReceiveMessage', (toUserID, message) => {
            // Toast('ReceiveMessage' + toUserID)
            let curRouteName = this.context.$route.name
            //企业
            if (curRouteName.indexOf('company') != -1) {
                if (curRouteName == 'company-im-window') {
                    this.context.$bus.$emit(Global.bus_company_im_message_receive_InsidePage);
                }
                //其它外部页面
                else {
                    this.context.$bus.$emit(Global.bus_company_im_message_receive_OutPage);
                }
            }
            //个人
            else if (curRouteName.indexOf('person') != -1) {
                if (curRouteName == 'person-im') {
                    this.context.$bus.$emit(Global.bus_pereson_im_message_receive_InsidePage);
                }
                //其它外部页面
                else {
                    this.context.$bus.$emit(Global.bus_pereson_im_message_receive_OutPage);
                }
            }
        });

        this.connection.start().then(() => {
            console.log('hub connect success');
            this.bindConnID(this.userID)
        }).catch(err => console.error('hub connect error:', err.toString()));

        this.connection.onreconnecting(error => {
            console.log(`Connection lost due to error "${error}". Reconnecting.`)
        })
        this.connection.onreconnected(connectionId => {
            this.bindConnID(this.userID)
        })
        this.connection.onclose(error => {
            console.log(`Connection closed due to error "${error}". Try refreshing this page to restart the connection.`)
        })

    },
    bindConnID(userID) {
        if (userID) {
            this.connection.invoke('BindIDs', userID)
                .then(() => {})
                .catch(err => console.error(err));
        }
    },
    sendHubMsg(toUserID, message) {
        this.connection.invoke('SendMessage', toUserID, message, this.userID)
            .then('sendHubMsg success')
            .catch(e => { console.log('sendHubMsg error', e) })
    }
}